/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * UIVietTat.java
 *
 * Created on Jun 18, 2011, 4:20:55 PM
 */
package Implementation.SourceCode.GUI;


import Implementation.SourceCode.DAL.DB_Access;
import Implementation.SourceCode.Utilities.CheckInput_IN;
import Implementation.SourceCode.Utilities.Utilities;
import java.awt.Font;
import java.awt.event.KeyEvent;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.Vector;
import javax.swing.JOptionPane;
import javax.swing.JTable;
import javax.swing.event.TableModelEvent;
import javax.swing.event.TableModelListener;
import javax.swing.table.DefaultTableModel;

/**
 *
 * @author mrkingdom75
 */
public class UIVietTat extends javax.swing.JFrame {
    
    private DefaultTableModel VTmodel;
    private DB_Access db;
    private String[] colName={"id","thu_tu","ten_viet_tat","ten_day_du"};
    /** Creates new form UIVietTat */
    public UIVietTat() {
        setTitle("Báo Cáo Chi - Quản Lý Tên Viết Tắt - © mrkingdom75@gmail.com");
        db = new DB_Access();
        initComponents();
        setExtendedState(MAXIMIZED_BOTH);
        loadTableVietTat();
        setConstraintField();
        txtThuTu.setText(db.lastID("viettat"));
        tblVietTat.setAutoResizeMode(JTable.AUTO_RESIZE_ALL_COLUMNS);
    }
    
    private void setConstraintField(){
        txtVietTat.setDocument(new CheckInput_IN(10, "qwertyuiopasdfghjklzxcvbnmQWERTYUIOPASDFGHJKLZXCVBNM1234567890"));
        txtThuTu.setDocument(new CheckInput_IN(3, "1234567890"));
    }
    
    private void loadTableVietTat(){
        try{
            Connection conn= db.getConnection(true);
            Statement stmt = conn.createStatement();
            ResultSet rs = stmt.executeQuery("select * from viettat order by vt_thu_tu");
            Vector<Vector> vVietTat = new Vector<Vector>();
            while(rs.next()){
                Vector dg = new Vector();
                dg.add(rs.getString("id"));
                dg.add(rs.getString("vt_thu_tu"));
                dg.add(rs.getString("ten_viet_tat"));
                dg.add(rs.getString("ten_day_du"));
                vVietTat.add(dg);
            }
            rs.close();
            conn.close();
            Vector<String> columnName = new Vector<String>();
            //columnName.add("ID");
            columnName.add("ID");
            columnName.add("Thứ Tự");
            columnName.add("Tên Viết Tắt");
            columnName.add("Tên Đầy Đủ");
            VTmodel = new DefaultTableModel(vVietTat, columnName){
                public boolean isCellEditable(int rowIndex, int mColIndex) {
                    if(mColIndex>0){
                        return true;
                    }return false;
                }
            };;
            //table.getColumnModel().getColumn(i)
            tblVietTat.setModel(VTmodel);
            int[] colSize = {100,100,150,800};
            int rowSize = 50;
            Utilities.setTableProperties(tblVietTat, rowSize, colSize, true);
            tblVietTat.setFont(new Font("Tahoma", 0, 30));
            tblVietTat.getModel().addTableModelListener(new TableModelListener() {
                @Override
                public void tableChanged(TableModelEvent e) {
                    if(tblVietTat.isEditing())        {
                        if(tblVietTat.getSelectedRow()!=-1 && tblVietTat.getSelectedColumn()!=-1){
                            if(!tblVietTat.getModel().getValueAt(tblVietTat.getSelectedRow(), tblVietTat.getSelectedColumn()).toString().isEmpty()){
                                String updateValue = tblVietTat.getModel().getValueAt(tblVietTat.getSelectedRow(), tblVietTat.getSelectedColumn()).toString();
                                String id = tblVietTat.getModel().getValueAt(tblVietTat.getSelectedRow(), 0).toString();
                                if(db.updateTableData("viettat" ,id, updateValue, colName[tblVietTat.getSelectedColumn()])){
                                    //JOptionPane.showMessageDialog( null , "Cập nhật dữ liệu : " + updateValue + " Thành Công");
                                }
                            }
                        }
                    }

                }
            });  
        }catch(Exception ex){
            ex.printStackTrace();
        }
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        panHeader = new javax.swing.JPanel();
        jLabel1 = new javax.swing.JLabel();
        panWest = new javax.swing.JPanel();
        panEast = new javax.swing.JPanel();
        panFooter = new javax.swing.JPanel();
        jButton2 = new javax.swing.JButton();
        panCenter = new javax.swing.JPanel();
        lblDienGiai = new javax.swing.JLabel();
        jLabel6 = new javax.swing.JLabel();
        txtVietTat = new javax.swing.JTextField();
        btnNhap = new javax.swing.JButton();
        jScrollPane1 = new javax.swing.JScrollPane();
        tblVietTat = new javax.swing.JTable();
        jLabel7 = new javax.swing.JLabel();
        txtThuTu = new javax.swing.JTextField();
        txtDayDu = new javax.swing.JTextField();
        lblBaoLoi = new javax.swing.JLabel();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        panHeader.setBackground(new java.awt.Color(0, 102, 0));
        panHeader.setPreferredSize(new java.awt.Dimension(400, 40));
        panHeader.setLayout(new java.awt.BorderLayout());

        jLabel1.setFont(new java.awt.Font("Tahoma", 1, 24));
        jLabel1.setForeground(new java.awt.Color(255, 255, 255));
        jLabel1.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
        jLabel1.setText("Viết Tắt");
        panHeader.add(jLabel1, java.awt.BorderLayout.CENTER);

        getContentPane().add(panHeader, java.awt.BorderLayout.NORTH);

        panWest.setBackground(new java.awt.Color(0, 102, 0));
        panWest.setPreferredSize(new java.awt.Dimension(20, 200));

        javax.swing.GroupLayout panWestLayout = new javax.swing.GroupLayout(panWest);
        panWest.setLayout(panWestLayout);
        panWestLayout.setHorizontalGroup(
            panWestLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 20, Short.MAX_VALUE)
        );
        panWestLayout.setVerticalGroup(
            panWestLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 363, Short.MAX_VALUE)
        );

        getContentPane().add(panWest, java.awt.BorderLayout.WEST);

        panEast.setBackground(new java.awt.Color(0, 102, 0));
        panEast.setPreferredSize(new java.awt.Dimension(20, 200));

        javax.swing.GroupLayout panEastLayout = new javax.swing.GroupLayout(panEast);
        panEast.setLayout(panEastLayout);
        panEastLayout.setHorizontalGroup(
            panEastLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 20, Short.MAX_VALUE)
        );
        panEastLayout.setVerticalGroup(
            panEastLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 363, Short.MAX_VALUE)
        );

        getContentPane().add(panEast, java.awt.BorderLayout.EAST);

        panFooter.setBackground(new java.awt.Color(0, 102, 0));

        jButton2.setFont(new java.awt.Font("Tahoma", 0, 24));
        jButton2.setText("Đóng");
        jButton2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton2ActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout panFooterLayout = new javax.swing.GroupLayout(panFooter);
        panFooter.setLayout(panFooterLayout);
        panFooterLayout.setHorizontalGroup(
            panFooterLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, panFooterLayout.createSequentialGroup()
                .addContainerGap(752, Short.MAX_VALUE)
                .addComponent(jButton2)
                .addGap(18, 18, 18))
        );
        panFooterLayout.setVerticalGroup(
            panFooterLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(panFooterLayout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jButton2)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        getContentPane().add(panFooter, java.awt.BorderLayout.SOUTH);

        panCenter.setBackground(new java.awt.Color(255, 255, 255));

        lblDienGiai.setFont(new java.awt.Font("Tahoma", 0, 24));
        lblDienGiai.setText("Tên Đầy Đủ:");

        jLabel6.setFont(new java.awt.Font("Tahoma", 0, 24));
        jLabel6.setText("Tên Viết Tắt:");

        txtVietTat.setFont(new java.awt.Font("Tahoma", 0, 36)); // NOI18N
        txtVietTat.setNextFocusableComponent(txtThuTu);
        txtVietTat.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyReleased(java.awt.event.KeyEvent evt) {
                txtVietTatKeyReleased(evt);
            }
        });

        btnNhap.setFont(new java.awt.Font("Tahoma", 0, 36));
        btnNhap.setText("Nhập");
        btnNhap.setNextFocusableComponent(tblVietTat);
        btnNhap.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnNhapActionPerformed(evt);
            }
        });
        btnNhap.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                btnNhapKeyPressed(evt);
            }
        });

        tblVietTat.setFont(new java.awt.Font("Tahoma", 0, 14));
        tblVietTat.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null}
            },
            new String [] {
                "Title 1", "Title 2", "Title 3", "Title 4"
            }
        ));
        tblVietTat.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyReleased(java.awt.event.KeyEvent evt) {
                tblVietTatKeyReleased(evt);
            }
        });
        jScrollPane1.setViewportView(tblVietTat);

        jLabel7.setFont(new java.awt.Font("Tahoma", 0, 24));
        jLabel7.setText("Thứ Tự:");

        txtThuTu.setFont(new java.awt.Font("Tahoma", 0, 36));
        txtThuTu.setNextFocusableComponent(txtDayDu);
        txtThuTu.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyReleased(java.awt.event.KeyEvent evt) {
                txtThuTuKeyReleased(evt);
            }
        });

        txtDayDu.setFont(new java.awt.Font("Tahoma", 0, 36));
        txtDayDu.setNextFocusableComponent(btnNhap);
        txtDayDu.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                txtDayDuKeyPressed(evt);
            }
        });

        lblBaoLoi.setFont(new java.awt.Font("Tahoma", 0, 24));
        lblBaoLoi.setForeground(new java.awt.Color(255, 0, 0));
        lblBaoLoi.setText("*");

        javax.swing.GroupLayout panCenterLayout = new javax.swing.GroupLayout(panCenter);
        panCenter.setLayout(panCenterLayout);
        panCenterLayout.setHorizontalGroup(
            panCenterLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(panCenterLayout.createSequentialGroup()
                .addContainerGap()
                .addGroup(panCenterLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(panCenterLayout.createSequentialGroup()
                        .addGroup(panCenterLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(lblDienGiai)
                            .addComponent(jLabel6))
                        .addGap(30, 30, 30)
                        .addGroup(panCenterLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, panCenterLayout.createSequentialGroup()
                                .addComponent(txtDayDu, javax.swing.GroupLayout.DEFAULT_SIZE, 509, Short.MAX_VALUE)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(btnNhap))
                            .addGroup(panCenterLayout.createSequentialGroup()
                                .addComponent(txtVietTat, javax.swing.GroupLayout.DEFAULT_SIZE, 237, Short.MAX_VALUE)
                                .addGap(18, 18, 18)
                                .addComponent(jLabel7)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                                .addComponent(txtThuTu, javax.swing.GroupLayout.DEFAULT_SIZE, 280, Short.MAX_VALUE))))
                    .addGroup(panCenterLayout.createSequentialGroup()
                        .addGap(23, 23, 23)
                        .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 734, Short.MAX_VALUE)
                        .addGap(44, 44, 44))
                    .addComponent(lblBaoLoi))
                .addContainerGap())
        );
        panCenterLayout.setVerticalGroup(
            panCenterLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, panCenterLayout.createSequentialGroup()
                .addGap(19, 19, 19)
                .addComponent(lblBaoLoi)
                .addGap(35, 35, 35)
                .addGroup(panCenterLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(txtVietTat, javax.swing.GroupLayout.PREFERRED_SIZE, 60, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel6)
                    .addComponent(jLabel7)
                    .addComponent(txtThuTu, javax.swing.GroupLayout.PREFERRED_SIZE, 60, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGroup(panCenterLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(panCenterLayout.createSequentialGroup()
                        .addGap(38, 38, 38)
                        .addComponent(lblDienGiai))
                    .addGroup(panCenterLayout.createSequentialGroup()
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addGroup(panCenterLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(txtDayDu, javax.swing.GroupLayout.PREFERRED_SIZE, 60, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(btnNhap))))
                .addGap(59, 59, 59)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 57, Short.MAX_VALUE)
                .addGap(33, 33, 33))
        );

        getContentPane().add(panCenter, java.awt.BorderLayout.CENTER);

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton2ActionPerformed
        // TODO add your handling code here:
        dispose();
}//GEN-LAST:event_jButton2ActionPerformed

    private void btnNhapActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnNhapActionPerformed
try{
        if(txtThuTu.getText().trim().isEmpty()){
            lblBaoLoi.setText("Thông Báo Lỗi : Chưa nhập \"Thứ Tự\" ");
            lblBaoLoi.setVisible(true);
            txtThuTu.requestFocus();
            return;
        }
        else if(txtVietTat.getText().trim().isEmpty()){
            lblBaoLoi.setText("Thông Báo Lỗi : Chưa nhập \"Tên Viết Tắt\" ");
            lblBaoLoi.setVisible(true);
            txtVietTat.requestFocus();
            return;
        }
        else if(txtDayDu.getText().trim().isEmpty()){
            lblBaoLoi.setText("Thông Báo Lỗi : Chưa nhập \"Tên Đầy Đủ\" ");
            lblBaoLoi.setVisible(true);
            txtDayDu.requestFocus();
            return;
        }
        // insert to database
            Connection conn = db.getConnection(true);
            Statement stmt = conn.createStatement();
            String id = db.lastID("viettat");
            String qInsert = "insert into viettat (id,vt_thu_tu,ten_viet_tat,ten_day_du) values (%s,%s,'%s','%s')";
            qInsert = String.format(qInsert, id,  txtThuTu.getText(), txtVietTat.getText(), txtDayDu.getText());
            
            int result = stmt.executeUpdate(qInsert) ;
            if(result==1){
                Vector<String> dg = new Vector<String>();
                dg.add(id);
                dg.add(txtThuTu.getText());
                dg.add(txtVietTat.getText());
                dg.add(txtDayDu.getText());
                VTmodel.insertRow(0, dg);            
                lblBaoLoi.setText("Nhập thành công tên viết tắt : "+ txtDayDu.getText());
                txtThuTu.requestFocus();
            }else{
                lblBaoLoi.setText("Lỗi kết nối ! Không thể ghi vào cơ sở dữ liệu");
            }
            conn.close();
        }catch(Exception ex){
            ex.printStackTrace();
        }        
    }//GEN-LAST:event_btnNhapActionPerformed

    private void txtDayDuKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_txtDayDuKeyPressed
        if(evt.getKeyCode() == KeyEvent.VK_ENTER && txtDayDu.getText().length()==0 ){
            btnNhap.requestFocus();
        }
        else if(evt.getKeyCode() == KeyEvent.VK_SPACE){
            txtDayDu.setText(txtDayDu.getText().substring(0,1).toUpperCase() + txtDayDu.getText().substring(1, txtDayDu.getText().length())  );
        }else if(evt.getKeyCode() == KeyEvent.VK_ENTER){
            txtDayDu.setText(txtDayDu.getText().substring(0,1).toUpperCase() + txtDayDu.getText().substring(1, txtDayDu.getText().length())  );
            btnNhap.requestFocus();
        }
    }//GEN-LAST:event_txtDayDuKeyPressed

    private void tblVietTatKeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_tblVietTatKeyReleased
        if(tblVietTat.getSelectedColumn()!=-1 && tblVietTat.getSelectedRow()!=-1){
            if(evt.getKeyCode()==KeyEvent.VK_DELETE){
                if( JOptionPane.OK_OPTION == JOptionPane.showConfirmDialog(this, "Bạn có muốn xóa dòng này không ? ")){
                    db.deleteRowById("viettat",tblVietTat.getModel().getValueAt(tblVietTat.getSelectedRow(), 0)+"");
                    VTmodel.removeRow(tblVietTat.getSelectedRow());
                }
            }
        }
    }//GEN-LAST:event_tblVietTatKeyReleased

    private void txtVietTatKeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_txtVietTatKeyReleased
        if(evt.getKeyCode() == KeyEvent.VK_ENTER){
            txtThuTu.requestFocus();
        }
    }//GEN-LAST:event_txtVietTatKeyReleased

    private void txtThuTuKeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_txtThuTuKeyReleased
        if(evt.getKeyCode() == KeyEvent.VK_ENTER){
            txtDayDu.requestFocus();
        }
    }//GEN-LAST:event_txtThuTuKeyReleased

    private void btnNhapKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_btnNhapKeyPressed
        if(evt.getKeyCode() == KeyEvent.VK_ENTER){
            btnNhap.doClick();
        }
    }//GEN-LAST:event_btnNhapKeyPressed

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {

            public void run() {
                new UIVietTat().setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnNhap;
    private javax.swing.JButton jButton2;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel6;
    private javax.swing.JLabel jLabel7;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JLabel lblBaoLoi;
    private javax.swing.JLabel lblDienGiai;
    private javax.swing.JPanel panCenter;
    private javax.swing.JPanel panEast;
    private javax.swing.JPanel panFooter;
    private javax.swing.JPanel panHeader;
    private javax.swing.JPanel panWest;
    private javax.swing.JTable tblVietTat;
    private javax.swing.JTextField txtDayDu;
    private javax.swing.JTextField txtThuTu;
    private javax.swing.JTextField txtVietTat;
    // End of variables declaration//GEN-END:variables
    private Connection openConnection(boolean commit){
        Connection conn = null;
        try{
            Class.forName("org.postgresql.Driver");
            conn = DriverManager.getConnection("jdbc:postgresql://localhost:5432/BaoCaoChi", "postgres", "qwer1234");
            conn.setAutoCommit(commit);
        }catch(Exception ex){
            ex.printStackTrace();
        }
        return conn;
    }
}
